﻿
//WebInvoke, invokes the server method.
LightScript.using("LightScript.Core", "LightScript.Net.WebRequest", "JSON@LightScript._Additions.JsonLib.jsonlib", function()
{
    LightScript.Core.createNamespace("LightScript.Net");
    var thisClass = LightScript.Core.createClass("LightScript.Net.WebInvoke");

    //# Private Members

    //# Constructions

    //# Public Members

    //# Private Methods

    //# Public Methods
    // Creates a web invoke, comma is not allowed in url parameter value.
    // extendParams<Object>: {invokeUri: "", urlParams: []}
    thisClass.create = create;
    function create(invokeClass, invokeMethod, invokeParamsAry, alwaysGetNew, onSuccess, onError, extendParams)
    {
        var invokeUri;
        if(extendParams && extendParams.invokeUri != undefined)  //From function parameter
            invokeUri = extendParams.invokeUri;
        if(!invokeUri)
            invokeUri = LightScript.Core.getConfig("invokeUri");   //From config

        var params = "class=" + (encodeURIComponent(invokeClass || LightScript.Core.getConfig("invokeClass"))) + 
                                "&method=" + encodeURIComponent(invokeMethod) + 
                                (invokeParamsAry ? "&params="+ encodeURIComponent(invokeParamsAry.join(",")) : "") + 
                                (extendParams && extendParams.urlParams ? "&extend=" + encodeURIComponent(extendParams.urlParams.join(",")) : "") + 
                                (alwaysGetNew ? ("&xrnd=" + Math.random()) : "");
        var requestUri = invokeUri + (invokeUri.indexOf("?") >= 0 ? "&" : "?") + params;

        LightScript.trace(requestUri);
        LightScript.Net.WebRequest.create(requestUri, null, 
            function(response){_onSucess(response, onSuccess);}, 
            onError, extendParams);
    }

    //# Private Event Handlers
    function _onSucess(response, onSuccess)
    {
        var json = JSON.parse(response.text);
        onSuccess(json);
    }

    //# Public Event Handlers

    //# Shortcuts
});
